#!/usr/bin/env ruby

# Copyright (c) 2010-2012 Microsoft Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#	http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

require 'net/http'
require 'uri'
require 'certified'

module Net
class HTTP
class << self
	alias_method :original_new, :new

	# redefine HTTP.new() to use a proxy if the http_proxy environment variable is defined
	# this implementation is inefficient, since it parses http_proxy every time
	def HTTP.new(address, port = nil, p_addr = nil, p_port = nil, p_user = nil, p_pass = nil)
		if ENV.has_key?('http_proxy')
			proxy_uri = URI.parse(ENV['http_proxy'])
			if proxy_uri.userinfo =~ /:/
				m = proxy_uri.userinfo.match(/(\w*):?(\w*)?/)
				if (m.length == 3)
					user = m[1]
					pass = m[2]
				else
					user = proxy_uri.userinfo
					pass = nil
				end

				original_new(address, port, proxy_uri.host, proxy_uri.port, user, pass)
			else
				original_new(address, port, proxy_uri.host, proxy_uri.port, proxy_uri.userinfo)
			end
		else
			original_new(address, port, p_addr, p_port, p_user, p_pass)
		end
	end
end # class << self
end # HTTP
end # Net

